package com.tianji.learning.mq;

import cn.hutool.core.collection.CollUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {

    final ILearningLessonService lessonService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "learning.lesson.pay.queue", durable = "true")
            , exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY))
    public void onMsg(OrderBasicDTO dto) {
        log.info("接收到消息，用户: {}，添加课程: {}", dto.getUserId(), dto.getCourseIds());
        //校验
        if (dto.getUserId() == null || dto.getOrderId() == null || CollUtil.isEmpty(dto.getCourseIds())) {
            //直接结束，不抛异常，否则会继续重试
            return;
        }
        //调用service，保存到课表
        lessonService.addUserLesson(dto.getUserId(), dto.getCourseIds());
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "learning.lesson.pay.queue", durable = "true")
            , exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY))
    public void onDeleteMsg(OrderBasicDTO dto) {
        log.info("接收到消息，用户: {}，添加课程: {}", dto.getUserId(), dto.getCourseIds());
        //校验
        if (dto.getUserId() == null || dto.getOrderId() == null || CollUtil.isEmpty(dto.getCourseIds())) {
            //直接结束，不抛异常，否则会继续重试
            return;
        }
        for (Long courseId : dto.getCourseIds()) {
            lessonService.deleteLessonByCId(courseId);
        }
    }

}
